import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { ContainerManager, ContainerStatus } from './containerManager';

/**
 * 实例配置接口
 */
export interface InstanceConfig {
    id?: string;
    name: string;
    containerName: string;
    port: number;
    configPath: string;
    status?: string;
}

/**
 * Nginx实例管理类
 */
export class InstanceManager {
    private instances: Map<string, InstanceConfig>;
    private activeInstanceId: string | null;
    private environment: any;
    private containerManager: ContainerManager;
    private storagePath: string;

    /**
     * 构造函数
     * @param context VSCode扩展上下文
     * @param environment 检测到的环境信息
     */
    constructor(private context: vscode.ExtensionContext, environment: any) {
        this.instances = new Map();
        this.activeInstanceId = null;
        this.environment = environment;
        this.containerManager = new ContainerManager(environment);
        this.storagePath = path.join(context.globalStoragePath, 'instances.json');
    }

    /**
     * 初始化实例管理器
     */
    async initialize(): Promise<void> {
        // 创建存储目录（如果不存在）
        const storageDir = path.dirname(this.storagePath);
        if (!fs.existsSync(storageDir)) {
            fs.mkdirSync(storageDir, { recursive: true });
        }

        // 加载已保存的实例
        await this.loadInstances();
    }

    /**
     * 加载已保存的实例
     */
    private async loadInstances(): Promise<void> {
        try {
            if (fs.existsSync(this.storagePath)) {
                const data = fs.readFileSync(this.storagePath, 'utf8');
                const savedData = JSON.parse(data);
                
                // 恢复实例
                if (savedData.instances) {
                    savedData.instances.forEach((instance: InstanceConfig) => {
                        if (instance.id) {
                            this.instances.set(instance.id, instance);
                        }
                    });
                }
                
                // 恢复活跃实例
                this.activeInstanceId = savedData.activeInstanceId || null;
            }
        } catch (error) {
            console.error('Failed to load instances:', error);
        }
    }

    /**
     * 保存实例
     */
    private async saveInstances(): Promise<void> {
        try {
            const instances = Array.from(this.instances.values());
            const data = {
                instances,
                activeInstanceId: this.activeInstanceId
            };
            
            fs.writeFileSync(this.storagePath, JSON.stringify(data, null, 2), 'utf8');
        } catch (error) {
            console.error('Failed to save instances:', error);
        }
    }

    /**
     * 创建新实例
     * @param config 实例配置
     * @returns 新创建的实例配置
     */
    async createInstance(config: InstanceConfig): Promise<InstanceConfig> {
        // 生成ID（如果没有提供）
        if (!config.id) {
            config.id = `nginx-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
        }
        
        // 设置初始状态
        config.status = 'stopped';
        
        // 保存实例
        this.instances.set(config.id, config);
        
        // 如果这是第一个实例，设为活跃实例
        if (!this.activeInstanceId) {
            this.activeInstanceId = config.id;
        }
        
        // 保存更改
        await this.saveInstances();
        
        return config;
    }

    /**
     * 删除实例
     * @param id 实例ID
     */
    async deleteInstance(id: string): Promise<void> {
        // 检查实例是否存在
        if (!this.instances.has(id)) {
            throw new Error(`Instance with id ${id} not found`);
        }
        
        // 获取实例
        const instance = this.instances.get(id)!;
        
        // 如果实例正在运行，先停止它
        if (instance.status === 'running') {
            await this.stopInstance(id);
        }
        
        // 删除实例
        this.instances.delete(id);
        
        // 如果被删除的是活跃实例，重置活跃实例
        if (this.activeInstanceId === id) {
            const remainingInstances = Array.from(this.instances.keys());
            this.activeInstanceId = remainingInstances.length > 0 ? remainingInstances[0] : null;
        }
        
        // 保存更改
        await this.saveInstances();
    }

    /**
     * 启动实例
     * @param id 实例ID
     * @returns 容器状态
     */
    async startInstance(id: string): Promise<ContainerStatus> {
        // 检查实例是否存在
        if (!this.instances.has(id)) {
            throw new Error(`Instance with id ${id} not found`);
        }
        
        // 获取实例
        const instance = this.instances.get(id)!;
        
        // 启动容器
        const status = await this.containerManager.startContainer({
            name: instance.containerName,
            port: instance.port,
            configPath: instance.configPath
        });
        
        // 更新实例状态
        instance.status = status.state;
        
        // 设为活跃实例
        this.activeInstanceId = id;
        
        // 保存更改
        await this.saveInstances();
        
        return status;
    }

    /**
     * 停止实例
     * @param id 实例ID
     */
    async stopInstance(id: string): Promise<void> {
        // 检查实例是否存在
        if (!this.instances.has(id)) {
            throw new Error(`Instance with id ${id} not found`);
        }
        
        // 获取实例
        const instance = this.instances.get(id)!;
        
        // 停止容器
        await this.containerManager.stopContainer(instance.containerName);
        
        // 更新实例状态
        instance.status = 'stopped';
        
        // 保存更改
        await this.saveInstances();
    }

    /**
     * 重启实例
     * @param id 实例ID
     */
    async restartInstance(id: string): Promise<ContainerStatus> {
        // 检查实例是否存在
        if (!this.instances.has(id)) {
            throw new Error(`Instance with id ${id} not found`);
        }
        
        // 获取实例
        const instance = this.instances.get(id)!;
        
        // 重启容器
        const status = await this.containerManager.restartContainer(instance.containerName);
        
        // 更新实例状态
        instance.status = status.state;
        
        // 设为活跃实例
        this.activeInstanceId = id;
        
        // 保存更改
        await this.saveInstances();
        
        return status;
    }

    /**
     * 获取活跃实例
     * @returns 活跃实例配置
     */
    getActiveInstance(): InstanceConfig | null {
        if (!this.activeInstanceId || !this.instances.has(this.activeInstanceId)) {
            return null;
        }
        
        return this.instances.get(this.activeInstanceId)!;
    }

    /**
     * 设置活跃实例
     * @param id 实例ID
     */
    async setActiveInstance(id: string): Promise<void> {
        // 检查实例是否存在
        if (!this.instances.has(id)) {
            throw new Error(`Instance with id ${id} not found`);
        }
        
        // 设置活跃实例
        this.activeInstanceId = id;
        
        // 保存更改
        await this.saveInstances();
    }

    /**
     * 获取所有实例
     * @returns 实例列表
     */
    getAllInstances(): InstanceConfig[] {
        return Array.from(this.instances.values());
    }

    /**
     * 获取实例
     * @param id 实例ID
     */
    getInstance(id: string): InstanceConfig | undefined {
        return this.instances.get(id);
    }

    /**
     * 更新实例配置
     * @param id 实例ID
     * @param config 新配置
     */
    async updateInstance(id: string, config: Partial<InstanceConfig>): Promise<InstanceConfig> {
        // 检查实例是否存在
        if (!this.instances.has(id)) {
            throw new Error(`Instance with id ${id} not found`);
        }
        
        // 获取实例
        const instance = this.instances.get(id)!;
        
        // 更新配置
        Object.assign(instance, config);
        
        // 保存更改
        await this.saveInstances();
        
        return instance;
    }
} 